﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CsRedisTest.Interfaces
{
    class MyJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            //仅在接口处进行转换
            if (objectType.IsInterface)
                return true;
            return false;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType.IsInterface)
            {
                //当声明类型是接口时，模拟从应用程序域读取所有实现类
                Type type = Assembly.GetExecutingAssembly().GetTypes().Where(x => objectType.IsAssignableFrom(x))
                    .Where(x => !x.IsAbstract)
                    .FirstOrDefault();
                return serializer.Deserialize(reader, type);
            }
            return serializer.Deserialize(reader, objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //正常序列化
            serializer.Serialize(writer, value);
        }
    }
}
